var express = require('express');
const annModel = require('../Model/annModel')
const alipaySdk = require('../utils/ailpaySdk');
const token = require('../utils/token')
const mailModel = require('../Model/mailModel')
const BuyModel = require('../Model/Buy')
const userBuyModel = require('../Model/userBuy')
const axios = require('axios')
var router = express.Router();


/* 添加公告 */
router.post('/addAnn', async (req, res, next) => {
  const { ann } = req.body
  const datanum = await annModel.find()
  if (datanum.length >= 6) return res.json({ code: '304', msg: '添加失败，最高添加6条数据' })
  await annModel.create({ data: ann })
  const data = await annModel.find()
  res.json({ code: '200', data })
})
/* 获取公告 */
router.post('/getAnn', async (req, res, next) => {
  const data = await annModel.find()
  res.json({ code: '200', data })
})
/* 删除公告 */
router.post('/deleteAnn', async (req, res, next) => {
  const { id } = req.body
  await annModel.deleteOne({ _id: id })
  const data = await annModel.find()
  res.json({ code: '200', data })
})
/* 获取订单数据 */
router.post('/getAlipaySdk', async (req, res, next) => {
  const { mail } = req.body
  const mailData = await mailModel.findOne({_id:mail})
  const data = await userBuyModel.find({mail:mailData.mail})
  res.json({ code: '200', data })
})
/* 手机支付创建 */
router.post('/ailpayM', token, async (req, res, next) => {

  const { money, data } = req.body
  //订单数据
  const bizContent = {
    out_trade_no: Date.now(),
    total_amount: money,
    subject: data,
    product_code: 'FAST_INSTANT_TRADE_PAY',
  }
  //创建订单
  //alipay.trade.page.pay电脑
  //alipay.trade.wap.pay手机
  const result = await alipaySdk.pageExecute('alipay.trade.wap.pay', 'GET', {
    bizContent,
    return_url: 'http://localhost:200/iSalipay',
    notify_url: 'http://101.32.169.227:3000/notifyM'
  });
  res.json({ code: '200', data: result })
})
/* 电脑支付创建 */
router.post('/ailpay', token, async (req, res, next) => {

  const { money, data } = req.body
  //订单数据
  const bizContent = {
    out_trade_no: Date.now(),
    total_amount: money,
    subject: data,
    product_code: 'FAST_INSTANT_TRADE_PAY',
  }
  //创建订单
  //alipay.trade.page.pay电脑
  //alipay.trade.wap.pay手机
  const result = await alipaySdk.pageExecute('alipay.trade.page.pay', 'GET', {
    bizContent,
    return_url: 'http://localhost:200/iSalipay',
    notify_url: 'http://101.32.169.227:3000/notify'
  });
  res.json({ code: '200', data: result })
})
//异步回调电脑
router.post('/notify', async (req, res, next) => {
  const { subject, out_trade_no,trade_no,total_amount } = req.body;
  //订单数据
  const bizContent = {
    out_trade_no,
    trade_no
  }
  const ifAlipay = async() => {
    console.log('支付成功');
    const num = await BuyModel.findOne({money:Math.floor(total_amount)})
    const userdata = await mailModel.findOne({mail:subject})
    const newData = Number(num.integral) + userdata.frequency
    await mailModel.findOneAndUpdate({mail:subject},{frequency:newData})
    await userBuyModel.create({id:out_trade_no,mail:subject,money:total_amount,frequency:num.frequency})
  }
  //发送支付宝axios
  const result = await alipaySdk.pageExecute('alipay.trade.query', 'GET', { bizContent });
  const data = await axios({ url: result, method: "get" })
  const datares = data.data.alipay_trade_query_response
    //判断是否成功
  if (datares.code === '10000') {
    switch (datares.trade_status) {
      case 'TRADE_SUCCESS':
           ifAlipay()
        break;
      case 'TRADE_FINISHED':
          ifAlipay()
        res.json({ code: '200', data: '支付成功,不可退款' })
        break;
      case 'WAIT_BUYER_PAY':
        res.json({ code: '300', data: '等待付款' })
        break;
      case 'TRADE_CLOSED':
        res.json({ code: '404', data: '未付款交易超时关闭' })
        break;
    }
  }
})
//异步回调手机
router.post('/notifyM', async (req, res, next) => {
  const { subject, out_trade_no,trade_no,total_amount } = req.body;
  //订单数据
  const bizContent = {
    out_trade_no,
    trade_no
  }
  const ifAlipay = async() => {
    console.log('支付成功');
    const num = await BuyModel.findOne({money:Math.floor(total_amount)})
    const userdata = await mailModel.findOne({_id:subject})
    const newData = Number(num.integral) + userdata.frequency
    await mailModel.findOneAndUpdate({_id:subject},{frequency:newData})
    await userBuyModel.create({id:out_trade_no,mail:subject,money:total_amount,frequency:num.frequency})
  }
  //发送支付宝axios
  const result = await alipaySdk.pageExecute('alipay.trade.query', 'GET', { bizContent });
  const data = await axios({ url: result, method: "get" })
  const datares = data.data.alipay_trade_query_response
    //判断是否成功
  if (datares.code === '10000') {
    switch (datares.trade_status) {
      case 'TRADE_SUCCESS':
           ifAlipay()
        break;
      case 'TRADE_FINISHED':
          ifAlipay()
        res.json({ code: '200', data: '支付成功,不可退款' })
        break;
      case 'WAIT_BUYER_PAY':
        res.json({ code: '300', data: '等待付款' })
        break;
      case 'TRADE_CLOSED':
        res.json({ code: '404', data: '未付款交易超时关闭' })
        break;
    }
  }
})


module.exports = router;
